﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Reflection;
using System.Threading;

namespace ERPForms
{
    public partial class DepartamenteFrm : FrmTreeRezumat
    {

        /// <summary>
        /// Daca este setata DenumireDepartament, macheta intra in adaugare cu denumirea completata
        /// </summary>
        private String _denumire = String.Empty;
        private Boolean Bugetara = false;
        public String DenumireDepartament
        {
            set
            {
                _denumire = value.ToUpper();
            }
        }

        public DepartamenteFrm(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();
            txtRoot = "Departamente";
            Filtru = "ORDER BY IDTipDepartament";
            localTree = departamenteTV;
            eSRPDataSet.Departamente.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSet.Departamente.IDDepartParinteColumn.DefaultValue = 0;
            eSRPDataSet.Departamente.ActivColumn.DefaultValue = true;
            eSRPDataSet.Departamente.ExecutieCheltuieliColumn.DefaultValue = false;
            eSRPDataSet.Departamente.OrdineColumn.DefaultValue = 0;
            HandleFillTree += new TreeLoadHandler(Frm_HandleFillTree);
            numeMacheta = Text;
            workConnString = mInfo.workConnectionString;
            ColoanaParinte = "IDDepartParinte";
        }

        void  Frm_HandleFillTree(object sender, TreeViewEventArgs e)
        {
            Trace.Assert(ModuleInfo.CodUnitate != -1, "Va rugam sa setati codul unitatii!");
            NodeInfo nd = e.Node.Tag as NodeInfo;
            if (ActivCB.Checked)
            {
                this.departamenteBindingSource.Filter = "IDDepartParinte = " + nd.ID.ToString() + " AND CodUnitate=" + ModuleInfo.CodUnitate.ToString() + " AND ACTIV=1 AND IDDepartament<>IDDepartParinte";
            }
            else
            {
                this.departamenteBindingSource.Filter = "IDDepartParinte = " + nd.ID.ToString() + " AND CodUnitate=" + ModuleInfo.CodUnitate.ToString() + " AND IDDepartament<>IDDepartParinte";
            }
             eSRPDataSet.Departamente.IDDepartParinteColumn.DefaultValue = Convert.ToInt32(nd.ID);
        }

        override public void Salvare(object sender, EventArgs args)
        {
            base.Salvare(sender, args);
            //if (NoRecUpdated!=0)
            //{
            //    ///incarca nodul modificat
            //    ///
            //    SqlConnection sqlC = DeschideConexiune(workConnString);
            //    this.tipDepartamentTableAdapter.Connection = sqlC;
            //    this.tipDepartamentTableAdapter.FillByActiv(eSRPDataSet.TipDepartament);
            //    InchideConexiune(sqlC);
            //}
        }
        
        private void DepartamenteFrm_Load(object sender, EventArgs e)
        {
            Trace.Assert(ModuleInfo.CodUnitate != -1, "Va rugam sa setati codul unitatii!");

            if (_denumire != String.Empty)
            {
                eSRPDataSet.Departamente.NumeColumn.DefaultValue = _denumire;
                departamenteDGV.AllowUserToAddRows = false;
            }

            this.listBndSourceMain.Add(departamenteBindingSource);
            this.listTableAdaptor.Add(departamenteTableAdapter.Adapter);
            
            this.tipDepartamentTableAdapter.Connection = DeschideConexiune(workConnString);
            this.gestionariTableAdapter.Connection = this.tipDepartamentTableAdapter.Connection;
            this.gestionariTableAdapter.Fill(this.eSRPDataSet.Gestionari);
            this.tipDepartamentTableAdapter.Fill(eSRPDataSet.TipDepartament);
            this.Filtru = " AND Activ=1";
            ///determinarea ultimului tip de departament folosit
            ///
            SqlCommand cmd = new SqlCommand("SELECT TOP 1 d.IDTipDepartament FROM [Departamente] d JOIN [TipDepartament] t ON d.IDTipDepartament=t.IDTipDepartament WHERE t.Activ=1 AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " ORDER BY IDDepartament DESC", this.tipDepartamentTableAdapter.Connection);
            Int32 idTipDep = 0;
            Object ret = cmd.ExecuteScalar();
            if (ret != null && ret != DBNull.Value)
            {
                idTipDep = Convert.ToInt32(ret);
                eSRPDataSet.Departamente.IDTipDepartamentColumn.DefaultValue = idTipDep;
            }
            ///determinarea ultimului gestionar folosit
            ///
            cmd.CommandText = "SELECT TOP 1 d.IDGestionar FROM [Departamente] d WHERE [CodUnitate]=" + ModuleInfo.CodUnitate.ToString() + " ORDER BY IDDepartament DESC";
            idTipDep = 0;
            ret = cmd.ExecuteScalar();
            if (ret != null  && ret!=DBNull.Value)
            {
                idTipDep = Convert.ToInt32(ret);
                eSRPDataSet.Departamente.IDGestionarColumn.DefaultValue = idTipDep;
            }

            InchideConexiune(departamenteTableAdapter.Connection);


            SetCurentUnit(ModuleInfo.CodUnitate);
            if (gestionariBindingSource.Count != 0)
            {
                AddButton("Gestionari", global::ERPStudio.Properties.Resources._001_56, Gestionari, ToolStripItemAlignment.Right, false);
                IDGestionarColumn.Visible = false;
            }

            
            if (_denumire != String.Empty)
                Adauga(this, null);

            Text = numeMacheta + " - " + ((departamenteTV.SelectedNode!=null)?departamenteTV.SelectedNode.Text:"");
            this.departamenteBindingSource.Sort = "IDTipDepartament";
            HandleSalvare += Salvare;
            AddButton("Parametrii", global::ERPStudio.Properties.Resources._001_07, Parametrii_Departamente, ToolStripItemAlignment.Right, true);
        }

        private void Parametrii_Departamente(object sender, EventArgs e)
        {
            DepartamenteParametriiFrm frm = new DepartamenteParametriiFrm(ModuleInfo);
            frm.ShowDialog();
            departamenteTableAdapter.Connection = DeschideConexiune(workConnString);
            departamenteTableAdapter.Fill(eSRPDataSet.Departamente,ModuleInfo.CodUnitate);
            InchideConexiune(departamenteTableAdapter.Connection);            
        }

        private void Gestionari(object sender, EventArgs e)
        {
            GestionariFrm frm = new GestionariFrm(ModuleInfo);
            frm.ShowDialog();
            gestionariTableAdapter.Connection = DeschideConexiune(workConnString);
            gestionariTableAdapter.Fill(eSRPDataSet.Gestionari);
            InchideConexiune(gestionariTableAdapter.Connection);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (ActivCB.Checked)
                this.Filtru = " AND Activ =1";
            else
                this.Filtru = String.Empty;
            this.departamenteTV.Nodes.Clear();
            TreeNode tnRoot = this.departamenteTV.Nodes.Add(txtRoot);
            Int32 cod = 0;
            tnRoot.Tag = new NodeInfo(cod);
            SqlConnection con = DeschideConexiune(workConnString);
            LoadTree(tnRoot, con, String.Empty);
            InchideConexiune(con);
        }

        override public void SetCurentUnit(short vCodUnitate)
        {
            SqlConnection con = DeschideConexiune(workConnString);
            this.jurnaleTableAdapter.Connection = con;
            jurnaleTableAdapter.Fill(eSRPDataSet.Jurnale,vCodUnitate);
            this.departamenteTableAdapter.Connection = con;
            this.departamenteTableAdapter.Fill(eSRPDataSet.Departamente, vCodUnitate);
            this.departamenteBindingSource.Filter = "IDDepartParinte = 0" + " AND CodUnitate=" + vCodUnitate.ToString() + " AND ACTIV=1 AND IDDepartament<>IDDepartParinte";
            this.departamenteTV.Nodes.Clear();
            TreeNode tnRoot = this.departamenteTV.Nodes.Add(txtRoot);
            Int32 cod = 0;
            tnRoot.Tag = new NodeInfo(cod);
            ColoanaPK = "IDDepartament";
            ColoanaNume = "Nume";
            this.Filtru = " AND Activ =1";
            LoadTree(tnRoot,con, vCodUnitate.ToString());
            Setup(con);
            InchideConexiune(con);
        }

        private void departamenteDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == NumeColumn.Index)
                ReloadTree = true;
        }

        private void Setup(SqlConnection wConn)
        {
            Object ret = GetSetupValue("FaresSetup", "Bugetara", ModuleInfo.CodUnitate, wConn);
            Boolean val =false;
            if (ret != null && ret != DBNull.Value)
                val = Convert.ToBoolean(ret);
            else
            {
                while (ret == null)
                {
                    MessageBox.Show("Modulul Parteneri nu a fost configurat. \nVa rugam sa-l configurati!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    #region Configurare Modul Fares
                    FrmMainMdi frm = MdiParent as FrmMainMdi;
                    Assembly asm = frm.GetModule("fares");
                    if (asm == null)
                        return;
                    String numeClasa = "Fares.FaresSetupFrm";
                    Type mModule = asm.GetType(numeClasa);

                    if (mModule != null)
                    {
                        FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                           new object[] { ModuleInfo}, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;

                        newFrm.ShowDialog();
                    }
                    #endregion

                    ret = GetSetupValue("FaresSetup", "Bugetara", ModuleInfo.CodUnitate, wConn);
                }
                val = Convert.ToBoolean(ret); 
            }
            Bugetara = val;
            PaturiColumn.Visible = val;
            SuprafataColumn.Visible = val;
            IDJurnalColumn.Visible = val;
        }
        
        
    }
}

